package st.business.tepth.business.businfo;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import st.business.tepth.R;
import st.business.tepth.R2;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.BusWarnRecordBean;
import st.business.tepth.business.bean.NumberBean;
import st.business.tepth.business.bean.PagingBean;
import st.business.tepth.config.Url;
import st.business.tepth.debug.DataProvider;
import st.business.tepth.manager.UserManager;
import st.shadow.library.core.base.fragment.BaseFragment;
import st.shadow.library.core.net.callback.IError;
import st.shadow.library.core.net.callback.ISuccess;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.ui.recycler.BaseDecoration;

/**
 * @author zhangyu
 * @date 2019/2/27
 * 车辆信息-报警记录
 */
public class FragmentWarnHistory extends BaseFragment {
    public static FragmentWarnHistory newInstance() {
        return new FragmentWarnHistory();
    }

    @BindView(R2.id.recycler_view_footer)
    RecyclerView mRecyclerViewFooter;
    @BindView(R2.id.iv_left)
    ImageView mIvLeft;
    @BindView(R2.id.iv_right)
    ImageView mIvRight;
    @BindView(R2.id.tv_count)
    TextView mTvCount;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerViewContent;
    private int mIndex = 0;
    private boolean move = false;
    private LinearLayoutManager mLinearLayoutManager;
    private BusWarnRecordAdapter mWarnRecordAdapter;
    private FooterNumberAdapter mFooterNumberAdapter;
    private String mStartDate;
    private String mEndDate;
    private String mBusNumber;
    private int mPageNumber = 1;
    private final int PAGE_SIZE = 5;
    private Disposable mDisposable;
    private boolean isRequesting = false;
    private boolean hasDrawComplete = false;

    @Override
    public Object setLayout() {
        return R.layout.fragment_bus_info_warn_history;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mRecyclerViewFooter.setLayoutManager(mLinearLayoutManager =
                new LinearLayoutManager(_mActivity,
                        LinearLayoutManager.HORIZONTAL, false));
        mRecyclerViewFooter.addOnScrollListener(new RecyclerViewListener());


        mRecyclerViewContent.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecyclerViewContent.setAdapter(mWarnRecordAdapter =
                new BusWarnRecordAdapter(R.layout.item_bus_info_warn_history
                        , DataProvider.getBusWarnRecordList()));
        mWarnRecordAdapter.setEmptyView(R.layout.view_search_empty,
                (ViewGroup) mRecyclerViewContent.getParent());
        mRecyclerViewContent.addItemDecoration(BaseDecoration.
                create(Color.parseColor("#f0f0f0"), 1));
        RecyclerView.ItemAnimator itemAnimator = mRecyclerViewFooter.getItemAnimator();
        if (itemAnimator != null) {
            itemAnimator.setChangeDuration(0);
        }
        mRecyclerViewFooter.setAdapter(mFooterNumberAdapter =
                new FooterNumberAdapter(R.layout.item_indictor_number, null,
                        new OnItemChooseListener<NumberBean>() {
                            @Override
                            public void onChoose(NumberBean numberBean) {
                                //mFooterNumberAdapter.addData();
                                //只能单页替换数据，不能滚动
                                if (mPageNumber != numberBean.getNumber()) {
                                    mPageNumber = numberBean.getNumber();
                                    localSearch(false);
                                    mTvCount.setText(String.format
                                            (Locale.CHINA, "%d/%d", numberBean.getNumber(),
                                                    mFooterNumberAdapter.getItemCount()));
                                }
                            }
                        }));
        mRecyclerViewFooter.addItemDecoration(BaseDecoration.
                create(Color.parseColor("#ffffff"), 10));
        onLeftClick();
        mTvCount.setText(String.format(Locale.CHINA, "%d/%d", 1, 20));
        showCountEnable(false);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        hasDrawComplete = true;
    }

    @OnClick(R2.id.iv_left)
    public void onLeftClick() {
        move(0);
        setBtnEnable(false, true);
    }

    @OnClick(R2.id.iv_right)
    public void onRightClick() {
        move(mFooterNumberAdapter.getItemCount() - 1);
        setBtnEnable(true, false);
    }

    private void setBtnEnable(boolean left, boolean right) {
        mIvLeft.setEnabled(left);
        mIvLeft.setBackgroundResource(left ?
                R.drawable.selector_left_number_indicator
                : R.drawable.ic_indicator_left_un_enable);

        mIvRight.setEnabled(right);
        mIvRight.setBackgroundResource(right ?
                R.drawable.selector_right_number_indicator
                : R.drawable.ic_indicator_right_un_enable);
    }

    private void move(int n) {
        if (n < 0 || n >= mFooterNumberAdapter.getItemCount()) {
            return;
        }
        mIndex = n;
        mRecyclerViewFooter.stopScroll();
        smoothMoveToPosition(n);
        mTvCount.setText(String.format
                (Locale.CHINA, "%d/%d", n + 1, mFooterNumberAdapter.getItemCount()));
    }

    private void smoothMoveToPosition(int n) {
        int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerViewFooter.smoothScrollToPosition(n);
        } else if (n <= lastItem) {
            int left = mRecyclerViewFooter.getChildAt(n - firstItem).getLeft();
            mRecyclerViewFooter.smoothScrollBy(left, 0);
        } else {
            mRecyclerViewFooter.smoothScrollToPosition(n);
            move = true;
        }

    }

    private void moveToPosition(int n) {
        int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerViewFooter.scrollToPosition(n);
        } else if (n <= lastItem) {
            int left = mRecyclerViewFooter.getChildAt(n - firstItem).getLeft();
            mRecyclerViewFooter.scrollBy(left, 0);
        } else {
            mRecyclerViewFooter.scrollToPosition(n);
            move = true;
        }

    }

    class RecyclerViewListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (move && newState == RecyclerView.SCROLL_STATE_IDLE) {
                move = false;
                int n = mIndex - mLinearLayoutManager.findFirstVisibleItemPosition();
                if (0 <= n && n < mRecyclerViewFooter.getChildCount()) {
                    int left = mRecyclerViewFooter.getChildAt(n).getLeft();
                    mRecyclerViewFooter.smoothScrollBy(left, 0);
                }

            }
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (move) {
                move = false;
                int n = mIndex - mLinearLayoutManager.findFirstVisibleItemPosition();
                if (0 <= n && n < mRecyclerViewFooter.getChildCount()) {
                    int left = mRecyclerViewFooter.getChildAt(n).getLeft();
                    mRecyclerViewFooter.scrollBy(left, 0);
                }
            }
        }
    }

    public void search(String busNumber, String startDate, String endDate) {
        mBusNumber = busNumber;
        mStartDate = startDate;
        mEndDate = endDate;
        mPageNumber = 1;
        localSearch(true);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }

    private void localSearch(final boolean isRefresh) {
        if (!isRequesting) {
            isRequesting = true;
            //是否正在请求
            mDisposable = RxRestClient.builder()
                    .url(Url.GetBusWarnRecord)
                    .params("token", UserManager.getInstance().getToken())
                    .params("busNo", mBusNumber)
                    .params("startDate", mStartDate)
                    .params("endDate", mEndDate)
                    .params("pageNumber", mPageNumber)
                    .params("pageSize", PAGE_SIZE)
                    .success(new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            if (mWarnRecordAdapter == null || mFooterNumberAdapter == null
                                    || mTvCount == null) {
                                return;
                            }
                            PagingBean<BusWarnRecordBean> pagingBean
                                    = new ObjConverter<PagingBean<BusWarnRecordBean>>().convert(response
                                    , new TypeReference<PagingBean<BusWarnRecordBean>>() {
                                    });
                            if (pagingBean != null) {
                                mWarnRecordAdapter.setNewData(pagingBean.getList());
                                if (isRefresh) {
                                    mFooterNumberAdapter.setNewData
                                            (makeNumber(pagingBean.getTotalPage()));
                                    mTvCount.setText(String.format
                                            (Locale.CHINA, "%d/%d", 1, pagingBean.getTotalPage()));
                                }
                                if (pagingBean.getTotalPage() == 0) {
                                    showCountEnable(false);
                                } else {
                                    showCountEnable(true);
                                }
                            } else {
                                mWarnRecordAdapter.setNewData(null);
                                mFooterNumberAdapter.setNewData(null);
                                showCountEnable(false);
                            }
                            isRequesting = false;
                        }
                    })
                    .error(new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            isRequesting = false;
                            showCountEnable(false);
                        }
                    })
                    .build()
                    .get();
        }
    }

    private List<NumberBean> makeNumber(int count) {
        final List<NumberBean> list = new ArrayList<>();
        for (int i = 1; i < count + 1; i++) {
            list.add(new NumberBean(i == 1, i));
        }
        return list;
    }

    private void showCountEnable(boolean enable) {
        if (mIvLeft != null && mIvRight != null && mTvCount != null) {
            if (!enable) {
                mIvLeft.setVisibility(View.INVISIBLE);
                mIvRight.setVisibility(View.INVISIBLE);
                mTvCount.setVisibility(View.INVISIBLE);
            } else {
                mIvLeft.setVisibility(View.VISIBLE);
                mIvRight.setVisibility(View.VISIBLE);
                mTvCount.setVisibility(View.VISIBLE);
            }
        }
    }
}
